package com.lin.benchmade.ts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简繁转换的类。googlecode上找的。实现很简单，就是用一个字典。
 * @author xiaolin
 *
 */
public class JChineseConvertor {

	private Map<Character, Character> ts;
	private Map<Character, Character> st;
	private static JChineseConvertor convertor = null;

	/**
	 * Get a JChineseConvertor instance. <br>
	 * <br>
	 * Actually, JChineseConvertor just load the Conversion Table from disk once
	 * while the first JChineseConvertor be instanced, and sequential call of
	 * the method will get a same instance
	 * 
	 * @exception IOException
	 *                if the conversion table cannot be loaded
	 */
	public static JChineseConvertor getInstance() {
		if (convertor == null) {
			try {
				convertor = new JChineseConvertor();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return convertor;
	}

	/**
	 * Convert all the characters of given String from Traditional Chinese to
	 * Simplified
	 */
	public String t2s(final String s) {
		char[] cs = new char[s.length()];
		for (int i = 0; i < s.length(); i++) {
			cs[i] = t2s(s.charAt(i));
		}
		return (new String(cs));
	}

	/**
	 * Convert all the characters of given String from Simplified Chinese to
	 * Traditional
	 */
	public String s2t(final String s) {
		char[] cs = new char[s.length()];
		for (int i = 0; i < s.length(); i++) {
			cs[i] = s2t(s.charAt(i));
		}
		return (new String(cs));
	}

	/**
	 * Convert a character from Traditional Chinese to Simplified. <br>
	 * if the given character cannot be converted, simple return the given
	 * character
	 */
	public Character t2s(final char c) {
		if (ts.get(c) == null) {
			return (c);
		}
		return (ts.get(c));
	}

	/**
	 * Convert a character from Simplified Chinese to Traditional <br>
	 * if the given character cannot be converted, simple return the given
	 * character
	 */
	public Character s2t(final char c) {
		if (st.get(c) == null) {
			return (c);
		}
		return (st.get(c));
	}

	private JChineseConvertor() throws IOException {
		List<Character> content = new ArrayList<Character>();
		BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("TS.table"), "utf-8"));
		int c;
		while ((c = in.read()) != -1) {
			content.add((char) c);
		}
		in.close();
		ts = new HashMap<Character, Character>();
		st = new HashMap<Character, Character>();
		for (int i = 0; i < content.size(); i = i + 2) {
			ts.put(content.get(i), content.get(i + 1));
			st.put(content.get(i + 1), content.get(i));
		}
	}
}